<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>BrowserRouter 原理</title>
    <style>
        #result{
            width: 400px;
            height: 300px;
            border:solid 1px #666;
        }
    </style>
</head>
<body>
    <div>
        <a href="/home">Home</a>
        <a href="/about">About</a>
        <hr>
        <div id="result"></div>

        <script>
            //获取两个 a 元素
            let links = document.querySelectorAll('a');
            let result = document.querySelector("#result");

            //绑定事件
            links.forEach(item => {
                //
                item.onclick = function(e){
                    //阻止默认行为
                    e.preventDefault();
                    //修改网页的 URL    state
                    history.pushState({id: 100}, '', this.href);
                    //查看当前历史的值
                    console.log(history);
                    //获取当前网页 URL 的路径
                    let {pathname} = location;
                    //根据 pathname 决定 result 的显示内容
                    switch(pathname){
                        case '/home':
                            result.innerHTML = 'Home Home Home';
                            break;
                        case '/about':
                            result.innerHTML = 'about about about';
                            break;
                        default:
                            result.innerHTML = '404 Not Found';
                    }
                }
            }); 

            //绑定事件  popstate 事件 弹出一个历史状态的时候, 自动触发
            window.addEventListener('popstate', function(){
                //获取当前网页 URL 的路径
                let {pathname} = location;
                //根据 pathname 决定 result 的显示内容
                switch(pathname){
                    case '/home':
                        result.innerHTML = 'Home Home Home';
                        break;
                    case '/about':
                        result.innerHTML = 'about about about';
                        break;
                    default:
                        result.innerHTML = '404 Not Found';
                }
            })
        </script>

    </div>
</body>
</html>